package com.example.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.HttpResponseEnum;
import com.example.common.utils.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

/**
 * 异常处理 配置
 */
@RestControllerAdvice
public class GlobalException {

    private static final Logger log = LoggerFactory.getLogger(GlobalException.class);

    

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                              HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return ResponseResult.fail(HttpResponseEnum.REQUEST_MODE_ERROR);
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ResponseResult HttpMediaTypeNotSupportedException() {
        return ResponseResult.fail(HttpResponseEnum.REQUEST_MODE_ERROR);
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public ResponseResult handleServiceException(ServiceException e) {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        return ObjectUtil.isNotNull(code) ? ResponseResult.fail(code, e.getMessage()) : ResponseResult.fail(e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public ResponseResult notLoginException(NotLoginException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        int errCode = e.getCode();
        /*
          11001	未能读取到有效Token
          11002	登录时的账号id值为空
          11003	更改 Token 指向的 账号Id 时，账号Id值为空
          11011	未能读取到有效Token
          11012	Token无效
          11013	Token已过期
          11014	Token已被顶下线
          11015	Token已被踢下线
          11016	Token已被冻结
         */
        if (errCode == 11001 || errCode == 11011 || errCode == 11012 || errCode == 11013) {
            log.error("请求地址'{}',发生系统异常. 异常码 {}", requestURI, e.getCode());
            return ResponseResult.fail(HttpResponseEnum.NOT_LOGIN_ERROR);
        }

        log.error("请求地址'{}',发生系统异常. 异常码 {}", requestURI, e.getCode());
        return ResponseResult.fail(e.getMessage());
    }

    /**
     * 自定义验证异常处理
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        return e.getBindingResult().getAllErrors().stream()
                .findFirst()
                .map(error -> ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR.getCode(), error.getDefaultMessage()))
                .orElse(ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR));
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResponseResult constraintDeclarationExceptionHandler(ConstraintViolationException e) {
        return e.getConstraintViolations().stream()
                .findFirst()
                .map(violation -> ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR.getCode(), violation.getMessage()))
                .orElse(ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR));
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public ResponseResult missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        return ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = IllegalStateException.class)
    public ResponseResult illegalStateExceptionHandler(IllegalStateException e) {
        return ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = BindException.class)
    public ResponseResult bindExceptionHandler(BindException e) {
        return e.getBindingResult().getFieldErrors().stream()
                .findFirst()
                .map(error -> ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR.getCode(), error.getDefaultMessage()))
                .orElse(ResponseResult.fail(HttpResponseEnum.PARAMS_ERROR));
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return ResponseResult.fail(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResponseResult.fail(e.getMessage());
    }

}
